﻿using FPSO.Models.Constant;
using FPSO.Models.ViewModel.TaskManage;
using PDB.DotNetSDK;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FPSO.Services.Impl
{
    public class ShipStateService
    {
        public string ConnStr { get; set; }
        public string TableName { get; set; }
        private PDBConnection conn = null;

        private Dictionary<long, string> id2NameDic;

        public ShipStateService(string connStr, string tableName)
        {
            ConnStr = connStr;
            TableName = tableName;
            id2NameDic = null;
        }

        /// <summary>
        /// 获取船上当前舱室状态
        /// </summary>
        /// <returns></returns>
        public ShipTankSnapState GetShipTankSnapState()
        {
            CreatePDBConnection();
            if (id2NameDic == null)
            {
                //需要初始化点信息
                InitId2NameDic();
            }

            string querySql = string.Format("SELECT * FROM {0}.snapshot WHERE devid IN ({1})", 
                TableName, string.Join(",", id2NameDic.Keys.ToList()));
            PDBCommand cmd = conn.CreateCommand();
            DataTable dt = cmd.ExecuteQuery(querySql);
            ShipTankSnapState shipState = new ShipTankSnapState();
            List<TankConstant.ConstantTankInfo> constantlist = TankConstant.ConstantList;

            foreach (DataRow dr in dt.Rows)
            {
                long devid = Convert.ToInt64(dr["devid"]);
                DateTime tstamp = Convert.ToDateTime(dr["tstamp"]);
                int val = Convert.ToInt32(dr["val"]);
                int quality = Convert.ToInt32(dr["quality"]);

                string tagName = id2NameDic[devid];
                string[] tagParts = tagName.Split('.');
                string tankId = TankConstant.GetTankId(tagName);
                
                TankStates tankState = shipState.GetTankStates(tankId);
                if (tankState == null)
                {
                    tankState = new TankStates();
                    shipState.AddTankStates(tankId, tankState);
                }

				//DEBUG 这下面的三个0.001是什么系数？？？
                if (tagParts[1].Equals("VOLM"))
                {
                    tankState.Volume.TStamp = tstamp;
                    tankState.Volume.Value = val * 0.001d;
                    tankState.Volume.Quality = quality;
                }
                else if (tagParts[1].Equals("LEVEL"))
                {
                    tankState.Level.TStamp = tstamp;
                    tankState.Level.Value = val * 0.001d;
                    tankState.Level.Quality = quality;
                }
                else if (tagParts[1].Equals("RATE"))
                {
                    tankState.Rate.TStamp = tstamp;
                    tankState.Rate.Value = val * 0.001d;
                    tankState.Rate.Quality = quality;
                }
            }

            return shipState;
        }

        private void InitId2NameDic()
        {
            string querySql = string.Format("SELECT * FROM sys_dev WHERE tabname = '{0}' AND devname LIKE 'NO%' LIMIT 10000", TableName);
            PDBCommand cmd = conn.CreateCommand();
            DataTable dt = cmd.ExecuteQuery(querySql);
            id2NameDic = new Dictionary<long, string>();
            foreach(DataRow dr in dt.Rows)
            {
                string tagName = dr["devname"].ToString();
                long tagId = Convert.ToInt64(dr["devid"]);
                if (tagName.EndsWith(".VOLM") || tagName.EndsWith(".LEVEL") || tagName.EndsWith(".RATE"))
                {
                    id2NameDic.Add(tagId, tagName);
                }
            }
        
        }

        private void CreatePDBConnection()
        {
            if (conn == null)
            {
                PDBConnection tmpConn = new PDBConnection(ConnStr);
                tmpConn.Open();
                conn = tmpConn;
            }
        }
    }
}
